/**
 *
 */
package pl.pawluk.inz.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import pl.pawluk.inz.dao.IGenericDao;

import java.io.Serializable;
import java.util.List;

/**
 * @author mandp
 */
@Transactional
public abstract class GenericDao<E, PK extends Serializable> implements IGenericDao<E, PK> {

    private final Class<E> clazz;
//    @Autowired
    SessionFactory sessionFactory;


    protected final Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    public GenericDao(final Class<E> clazzToSet) {
        this.clazz = clazzToSet;
    }

    @SuppressWarnings("unchecked")
    @Override
    public PK save(E newInstance) {
        return (PK) getCurrentSession().save(newInstance);
    }


    @Override
    public E findById(PK id) {
        return (E) getCurrentSession().get(clazz, id);
    }


    @Override
    public List<E> findAll() {
        return getCurrentSession().createQuery("from " + this.clazz.getName()).list();

    }


    @Override
    public void update(E transientObject) {
        getCurrentSession().update(transientObject);
    }


    @Override
    public void saveOrUpdate(E transientObject) {
        getCurrentSession().saveOrUpdate(transientObject);
        getCurrentSession().flush();
    }


    @Override
    public void delete(E persistentObject) {
        getCurrentSession().delete(persistentObject);
    }


    protected Criteria createCriteria() {
        return getCurrentSession().createCriteria(clazz);
    }


    @Override
    public Long countByCriteria(Criteria dc) {
        return (Long) dc.setProjection(Projections.rowCount()).uniqueResult();
    }
}
